package com.hyacinth.forumbite.controller;

import com.github.pagehelper.PageInfo;
import com.hyacinth.forumbite.common.AppConfig;
import com.hyacinth.forumbite.common.AppResult;
import com.hyacinth.forumbite.common.ResultCode;
import com.hyacinth.forumbite.exception.ApplicationException;
import com.hyacinth.forumbite.model.Article;
import com.hyacinth.forumbite.model.Board;
import com.hyacinth.forumbite.model.User;
import com.hyacinth.forumbite.service.ArticleService;
import com.hyacinth.forumbite.service.BoardService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Yun
 * @Date: 2025/5/22
 */
@Slf4j
@Tag(name = "帖子相关接口")
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private ArticleService articleService;
    @Resource
    private BoardService boardService;

    @Operation(summary = "发布帖子")
    @PostMapping("/create")
    @Parameters({
            @Parameter(name = "boardId", description = "板块id"),
            @Parameter(name = "title", description = "标题"),
            @Parameter(name = "content", description = "内容")
    })
    public AppResult create(HttpServletRequest request, @RequestParam("boardId") @NonNull Long boardId,
                            @RequestParam("title") @NonNull String title, @RequestParam("content") @NonNull String content) {

        // 1.检查用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Board board = boardService.selectById(boardId);
        if (board == null || board.getState() == 1 || board.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_STATE.toString());
            return AppResult.failed(ResultCode.FAILED_BOARD_STATE);
        }

        Article article = new Article()
                .setContent(content)
                .setTitle(title)
                .setBoardId(boardId)
                .setUserId(user.getId());

        articleService.create(article);
        return AppResult.success();
    }

    @Operation(summary = "根据板块id获取帖子列表")
    @GetMapping("/list")
    @Parameters({
            @Parameter(name = "id", description = "板块id", required = false)
    })
    public AppResult<List<Article>> selectListByBoardId(@RequestParam(value = "boardId", required = false) Long boardId) {
        List<Article> articles = null;
        if (boardId == null) {
            articles = articleService.selectAll();
        } else {
            articles = articleService.selectAllByBoardId(boardId);
        }
        if (articles == null) {
            return AppResult.success(new ArrayList<>());
        }
        return AppResult.success(articles);
    }

    @Operation(summary = "根据帖子id查询帖子详情")
    @Parameters({
            @Parameter(name = "id", description = "帖子id")
    })
    @GetMapping("/details")
    public AppResult selectDetailsById(HttpServletRequest request, @RequestParam("id") Long id) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        Article article = articleService.selectDetailsById(id);
        if (article == null) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if (user.getId().equals(article.getUserId())) {
            article.setOwn(true);
        }
        return AppResult.success(article);
    }

    @Operation(summary = "修改帖子")
    @Parameters({
            @Parameter(name = "id", description = "帖子id"),
            @Parameter(name = "title", description = "标题"),
            @Parameter(name = "content", description = "正文")
    })
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request, @RequestParam("id") @NonNull Long id, @RequestParam("title") @NonNull String title, @RequestParam("content") @NonNull String content) {
        // 获取用户信息判断用户是否是作者 用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 判断帖子是否存在 帖子的状态
        Article article = articleService.selectByPrimaryKey(id);
        if (article == null) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if (!user.getId().equals(article.getUserId())) {
            return AppResult.failed(ResultCode.FAILED);
        }
        if (article.getState() == 1 || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_STATE);
        }
        articleService.modify(id, title, content);
        return AppResult.success();
    }

    @Operation(summary = "点赞")
    @PostMapping("/addLikeCount")
    public AppResult addLikeCount(HttpServletRequest request, @RequestParam("id") @NonNull Long id) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        articleService.addLikeCount(id);
        return AppResult.success();
    }


    @Operation(summary = "点赞(一人一赞)")
    @Parameters({
            @Parameter(name = "articleId", description = "帖子id")
    })
    @PostMapping("/like")
    public AppResult<Boolean> like(HttpServletRequest request, @RequestParam("articleId") @NonNull Long articleId) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        boolean like = articleService.like(user.getId(), articleId);
        return AppResult.success(like);
    }

    @Operation(summary = "点赞的帖子列表")
    @GetMapping("/likeArticles")
    public AppResult<PageInfo<Article>> likeArticles(HttpServletRequest request,
                                                     @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                                     @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        return AppResult.success(articleService.likeArticles(user.getId(), pageNum, pageSize));
    }

    @Operation(summary = "根据帖子id删除帖子")
    @Parameters({
            @Parameter(name = "id", description = "帖子id")
    })
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request, @RequestParam("id") Long id) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        Article article = articleService.selectByPrimaryKey(id);
        if (!user.getId().equals(article.getUserId())) {
            return AppResult.failed(ResultCode.FAILED);
        }
        articleService.deleteById(id);
        return AppResult.success();
    }

    @Operation(summary = "根据用户id查询用户帖子列表")
    @Parameters({
            @Parameter(name = "id", description = "用户id")
    })
    @GetMapping("/listByUserid")
    public AppResult<List<Article>> selectListByUserId(HttpServletRequest request, @RequestParam(value = "userId", required = false) Long userId) {
        if (userId == null) {
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        return AppResult.success(articleService.getArticleListByUserId(userId));
    }
}
